﻿using ControlzEx.Standard;
using GpCommon;
using GpCommon.Helpers;
using GpCommon.Models;
using GPSpeedView.GPHelpers;
using GPSpeedView.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
using System.Web.Configuration;

namespace GPSpeedView.Views
{
    /// <summary>
    /// TestBtnView.xaml 的交互逻辑
    /// </summary>
    public partial class TestBtnView : Window
    {
        private string _CopyContent;
        public TestBtnView()
        {
            InitializeComponent();
            SettingTime();
        }
        //private DateTime? GetTime()
        //{
        //    string input = InputBox.Text;
        //    if (string.IsNullOrEmpty(input)) return null;
        //    var strs = input.Split('.');
        //    if (strs.Count() != 3) return null;
        //    int year = int.Parse(strs[0]);
        //    int month = int.Parse(strs[1]);
        //    int day = int.Parse(strs[2]);

        //    DateTime time = new DateTime(year, month, day);
        //    return time;
        //}
        private void SettingTime()
        {
            // 获取两年的信息
            var dayList = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(DateTime.Now.Year - 1, CommonData.TargetCode);
            dayList.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(DateTime.Now.Year, CommonData.TargetCode));

            //var dayList = GpNetDataHelper.GetHistoryDayInfoByCode(CommonData.TargetCode).Result;
            if (dayList.Count > 1)
            {
                var startTime = dayList[0].Time;
                datePicker.DisplayDateStart = startTime;
                datePicker.DisplayDateEnd = DateTime.Now;
                while (startTime.CompareTo(DateTime.Now) < 0)
                {
                    if (dayList.Find(x => x.Time == startTime) == null)
                    {
                        datePicker.BlackoutDates.Add(new CalendarDateRange(startTime));
                    }
                    startTime = startTime.AddDays(1);
                }
            }
        }
        private void HighShowBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (datePicker.SelectedDate == null) return;
                var date = (DateTime)datePicker.SelectedDate;
                int year = date.Year;
                int month = date.Month;
                int day = date.Day;
                var codes = GpLocalDataHelper.GetValidGpCodes();

                StringBuilder highClsSb = new StringBuilder();
                StringBuilder lowClsSb = new StringBuilder();
                int total = 0;
                int high = 0;
                int low = 0;
                foreach (var code in codes)
                {
                    var list = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(year, code);
                    var target = list.Find(x => x.Time.Month == month && x.Time.Day == day);
                    if (target != null)
                    {
                        var index = list.IndexOf(target);
                        var clsPrice = list[index - 1].ClsPrice;
                        if (target.HighPrice >= clsPrice * 1.095)
                        {
                            total++;
                            if (target.MarkUp > 9.5)
                            {
                                highClsSb.Append(code + ";  ");
                                high++;
                            }
                            else
                            {
                                lowClsSb.Append(code + ";  ");
                                low++;
                            }
                        }
                    }
                    OutputBox.Text = codes.Count + ":" + (codes.IndexOf(code) + 1);
                }

                highClsSb.Append($"\r\n total:{total};high:{high};low:{low}");
                lowClsSb.Append($"\r\n total:{total};high:{high};low:{low}");

                File.WriteAllText("HighList.txt", highClsSb.ToString());
                File.WriteAllText("LowList.txt", lowClsSb.ToString());

                MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TopShowBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (datePicker.SelectedDate == null) return;
                var time = (DateTime)datePicker.SelectedDate;
                if (time != null)
                {
                    GPTopView view = new GPTopView((DateTime)time);
                    view.Show();
                }
            }
            catch (Exception)
            {

            }
        }


        private void MoreRedBtn_Click(object sender, RoutedEventArgs e)
        {
            List<GpCurEntity> curList = new List<GpCurEntity>();
            if (CommonData.TotalGpCount == 0)
            {
                curList = GpNetDataHelper.GetAllCurGpData().Result;
            }
            curList = GpNetDataHelper.GetAllCurGpData().Result;

            var targetInfo = GpNetDataHelper.GetHistoryDayInfoByCode(CommonData.TargetCode).Result;
            var targetLocalInfo = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(DateTime.Now.Year, CommonData.TargetCode);

            bool isNetMode = false;
            int targetNum = 2;
            try
            {
                if (datePicker.SelectedDate == null) return;
                var time = (DateTime)datePicker.SelectedDate;
                if (time.Date == DateTime.Now.Date)
                {
                    isNetMode = true;
                }
                var list = GpLocalDataHelper.GetValidGpCodes();
                StringBuilder sb = new StringBuilder();
                int total = 0;
                float totalMarkup = 0;
                float totalHighMarkup = 0;
                int redmarkup = 0;
                int greenmarkup = 0;
                string copyStr = "";
                foreach (var item in list)
                {
                    var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                    dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                    if (dayEnts != null && dayEnts.Count > 0)
                    {

                        if (isNetMode)
                        {
                            if (dayEnts.Last().Time == time)
                                dayEnts.RemoveAt(dayEnts.Count - 1);
                            var tempEnt = curList.Find(x => x.Code == item);
                            if (tempEnt == null) continue;
                            dayEnts.Add(GpDayEntity.CreateFromGpCurEntity(tempEnt));
                        }

                        GetAverageLine(dayEnts);
                        var last = dayEnts.Last();
                        var index = dayEnts.FindIndex(x => x.Time == time);
                        if (index > targetNum)
                        {
                            bool isSuccess = true;
                            List<float> markUpList = new List<float>();
                            #region 方式1 多日小涨
                            //for (int i = 0; i < targetNum; i++)
                            //{
                            //    if (dayEnts[index - i].MarkUp < 1
                            //        || dayEnts[index - i].MarkUp > 8)
                            //    {
                            //        isSuccess = false;
                            //        break;
                            //    }
                            //    if (i > 0)
                            //    {
                            //        if (dayEnts[index - i + 1].HighPrice > dayEnts[index - i].ClsPrice * 1.08)
                            //        {
                            //            isSuccess = false;
                            //            break;
                            //        }
                            //        if (dayEnts[index - i + 1].HighPrice < dayEnts[index - i].HighPrice
                            //            || dayEnts[index - i + 1].LowPrice < dayEnts[index - i].LowPrice)
                            //        {
                            //            isSuccess = false;
                            //            break;
                            //        }
                            //    }
                            //    markUpList.Add(dayEnts[index - i].MarkUp);
                            //}
                            //if (isSuccess)
                            //{
                            //    if (!IsNoMoreLarge(markUpList, 0))
                            //    {
                            //        isSuccess = false;
                            //        continue;
                            //    }
                            //    if (dayEnts[index - targetNum].MarkUp > 0)
                            //    {
                            //        isSuccess = false;
                            //        continue;
                            //    }
                            //    if (dayEnts[index].Day5Price < dayEnts[index].Day10Price
                            //        || dayEnts[index].Day10Price < dayEnts[index].Day20Price
                            //        || dayEnts[index].Day20Price < dayEnts[index].Day30Price)
                            //    {
                            //        isSuccess = false;
                            //        continue;
                            //    }
                            //}
                            #endregion

                            #region 方式2
                            if (dayEnts[index].ClsPrice >= dayEnts[index].PrePrice
                                && dayEnts[index - 1].ClsPrice >= dayEnts[index - 1].PrePrice
                                && dayEnts[index - 2].ClsPrice >= dayEnts[index - 2].PrePrice
                                && dayEnts[index].Day5Price > dayEnts[index].Day20Price
                                && dayEnts[index].Day10Price > dayEnts[index].Day60Price)
                            {
                                isSuccess = true;
                            }
                            else
                            {
                                isSuccess = false;
                            }
                            #endregion
                            if (isSuccess)
                            {
                                if (dayEnts.Count > index + 1)
                                {
                                    float markup = dayEnts[index + 1].MarkUp;
                                    float maxMarkup = (dayEnts[index + 1].HighPrice / dayEnts[index].ClsPrice - 1) * 100;

                                    sb.Append(item + ": " + "涨幅：" + dayEnts[index + 1].MarkUp +
                                        "; 最高点涨幅" + maxMarkup.ToString("F2") +
                                        "; \n");
                                    total++;
                                    totalHighMarkup += maxMarkup;
                                    totalMarkup += markup;
                                    if (markup > 0)
                                    {
                                        redmarkup++;
                                    }
                                    else
                                    {
                                        greenmarkup++;
                                    }
                                }
                                copyStr += item + "   ";
                            }
                        }
                    }
                }
                sb.Append("总数：" + total + "; + " + redmarkup + "; - " + greenmarkup + "; 平均涨幅：" + totalMarkup / total + "; 最高点平均涨幅：" + totalHighMarkup / total);
                OutputBox.Text = sb.ToString();
                _CopyContent = copyStr;
                File.WriteAllText("MoreRed.txt", copyStr);
                MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool IsNoMoreLarge(List<float> list, float tol)
        {
            var max = list.Max();
            for (int i = 0; i < list.Count - 1; i++)
            {
                if (list[i] + list[i + 1] + tol < max)
                    return false;
            }
            return true;
        }

        private void GetAverageLine(List<GpDayEntity> result)
        {
            List<float> day5List = new List<float>();
            List<float> day10List = new List<float>();
            List<float> day20List = new List<float>();
            List<float> day30List = new List<float>();
            List<float> day60List = new List<float>();
            // 计算均线
            for (int i = 0; i < result.Count; i++)
            {
                day5List.Add(result[i].ClsPrice);
                day10List.Add(result[i].ClsPrice);
                day20List.Add(result[i].ClsPrice);
                day30List.Add(result[i].ClsPrice);
                day60List.Add(result[i].ClsPrice);
                if (day5List.Count == 6)
                {
                    day5List.RemoveAt(0);
                }
                if (day5List.Count == 5)
                {
                    float total5 = 0f;
                    day5List.ForEach(x => { total5 += x; });
                    result[i].Day5Price = (float)Math.Round(total5 / 5f, 2);
                }
                if (day10List.Count == 11)
                {
                    day10List.RemoveAt(0);
                }
                if (day10List.Count == 10)
                {
                    float total10 = 0f;
                    day10List.ForEach(x => { total10 += x; });
                    result[i].Day10Price = (float)Math.Round(total10 / 10f, 2);
                }
                if (day20List.Count == 21)
                {
                    day20List.RemoveAt(0);
                }
                if (day20List.Count == 20)
                {
                    float total20 = 0f;
                    day20List.ForEach(x => { total20 += x; });
                    result[i].Day20Price = (float)Math.Round(total20 / 20f, 2);
                }
                if (day30List.Count == 31)
                {
                    day30List.RemoveAt(0);
                }
                if (day30List.Count == 30)
                {
                    float total30 = 0f;
                    day30List.ForEach(x => { total30 += x; });
                    result[i].Day30Price = (float)Math.Round(total30 / 30f, 2);
                }
                if (day60List.Count == 61)
                {
                    day60List.RemoveAt(0);
                }
                if (day60List.Count == 60)
                {
                    float total60 = 0f;
                    day60List.ForEach(x => { total60 += x; });
                    result[i].Day60Price = (float)Math.Round(total60 / 60f, 2);
                }
            }

        }

        private void CopyBtn_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.Clear();
            //Clipboard.SetText(_CopyContent);
            Clipboard.SetDataObject(_CopyContent);
        }

        private void DownTwoBtn_Click(object sender, RoutedEventArgs e)
        {
            var targetInfo = GpNetDataHelper.GetHistoryDayInfoByCode(CommonData.TargetCode).Result;
            var targetLocalInfo = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(DateTime.Now.Year, CommonData.TargetCode);

            try
            {
                if (datePicker.SelectedDate == null) return;
                var time = (DateTime)datePicker.SelectedDate;
                if (time.Date != DateTime.Now.Date)
                {
                    MessageBox.Show("不支持");
                    return;
                }

                var list = GpLocalDataHelper.GetValidGpCodes();
                StringBuilder sb = new StringBuilder();
                int total = 0;
                float totalMarkup = 0;
                float totalHighMarkup = 0;
                int redmarkup = 0;
                int greenmarkup = 0;
                string copyStr = "";

                List<GpCurEntity> curList = new List<GpCurEntity>();
                if (CommonData.TotalGpCount == 0)
                {
                    curList = GpNetDataHelper.GetAllCurGpData().Result;
                }
                curList = GpNetDataHelper.GetAllCurGpData().Result;

                foreach (var item in list)
                {
                    //var dayEnts = AlGpHelper.GetHistoryDayInfoByCode(item).Result;

                    var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                    dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                    if (dayEnts != null && dayEnts.Count > 0)
                    {
                        if (dayEnts.Last().Time == time)
                            dayEnts.RemoveAt(dayEnts.Count - 1);
                        var tarData = curList.Find(x => x.Code == item);
                        if (tarData == null) continue;
                        bool isSuccess = false;
                        #region 方式2
                        if (dayEnts[dayEnts.Count - 2].MarkUp < 0
                            && dayEnts[dayEnts.Count - 1].MarkUp < 0)
                        {
                            total++;

                            if (/*tarData.CurMarkUp > 2*/
                                (tarData.CurPrice - tarData.PrePrice) / tarData.PrePrice > 0.02
                            && tarData.CurPrice >= dayEnts[dayEnts.Count - 1].PrePrice
                            && tarData.CurPrice < dayEnts[dayEnts.Count - 2].PrePrice)
                            {
                                isSuccess = true;
                            }
                        }
                        else
                        {
                            isSuccess = false;
                        }
                        #endregion
                        if (isSuccess)
                        {
                            copyStr += item + "   ";
                        }
                    }

                }
                sb.Append("总数：" + total + "; + " + redmarkup + "; - " + greenmarkup + "; 平均涨幅：" + totalMarkup / total + "; 最高点平均涨幅：" + totalHighMarkup / total);
                OutputBox.Text = sb.ToString();
                _CopyContent = copyStr;
                File.WriteAllText("MoreRed.txt", copyStr);
                MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void More95Btn_Click(object sender, RoutedEventArgs e)
        {
            if (datePicker.SelectedDate == null) return;
            var time = (DateTime)datePicker.SelectedDate;
            string copyStr = "";
            int total = 0;
            int highTotal = 0;
            float moreNum = 1.095f;
            double blTotal = 0;
            int num = 0;
            float kkTotal = 0;
            if (time.Date != DateTime.Now.Date)
            {
                var list = GpLocalDataHelper.GetValidGpCodes();

                do
                {
                    if (!datePicker.BlackoutDates.Contains(time))
                    {
                        total = 0;
                        highTotal = 0;
                        kkTotal = 0;
                        foreach (var item in list)
                        {
                            var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                            dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                            if (dayEnts != null && dayEnts.Count > 0)
                            {
                                var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                                if (tempEntIndex > 2)
                                {
                                    if (dayEnts[tempEntIndex].PrePrice >= dayEnts[tempEntIndex].HighPrice)
                                        continue;
                                    if (dayEnts[tempEntIndex].HighPrice > dayEnts[tempEntIndex - 1].ClsPrice * moreNum)
                                    {
                                        //copyStr += item + "   ";
                                        total++;
                                        if (dayEnts[tempEntIndex].ClsPrice >= dayEnts[tempEntIndex].HighPrice)
                                        {
                                            highTotal++;
                                        }
                                        else
                                        {
                                            var kk = (dayEnts[tempEntIndex].HighPrice - dayEnts[tempEntIndex].ClsPrice) / dayEnts[tempEntIndex - 1].ClsPrice;
                                            kkTotal += kk;
                                        }
                                    }
                                }
                            }
                        }
                        double bl = highTotal / (double)total;
                        blTotal += bl;
                        copyStr += string.Format("时间：{4}，总数：{0}，红数：{1}，绿树：{2},比率：{3},亏总：{5}，亏均：{6}",
                            total, highTotal, total - highTotal, bl.ToString("F2"), time.Date.ToString(), kkTotal, kkTotal / (float)(total - highTotal)) + "\r\n";
                        num++;
                    }
                    time = time.AddDays(1);
                } while (time.Date != DateTime.Now.Date);
                copyStr += "总天数" + num + ",平均：" + blTotal / (double)num;
            }
            else
            {
                List<GpCurEntity> curList = new List<GpCurEntity>();
                if (CommonData.TotalGpCount == 0)
                {
                    curList = GpNetDataHelper.GetAllCurGpData().Result;
                }
                curList = GpNetDataHelper.GetAllCurGpData().Result;

                StringBuilder sb = new StringBuilder();

                var list = GpLocalDataHelper.GetValidGpCodes();
                foreach (var item in curList)
                {
                    if (!list.Contains(item.Code)) continue;
                    if (item.HighPrice > item.YesClsPrice * moreNum)
                    {
                        total++;
                        if (item.CurPrice >= item.HighPrice)
                        {
                            highTotal++;
                        }
                        else
                        {
                            copyStr += item.Code + "   ";

                        }
                    }
                }
            }

            _CopyContent = copyStr;
            File.WriteAllText("MoreRed.txt", copyStr);
            MessageBox.Show(string.Format("总数：{0}，红数：{1}，绿树：{2}", total, highTotal, total - highTotal));
            MessageBox.Show("完成");
        }

        private void UpMore_Click(object sender, RoutedEventArgs e)
        {
            if (datePicker.SelectedDate == null) return;
            var time = (DateTime)datePicker.SelectedDate;
            string copyStr = "";
            int total = 0;
            int num = 2;
            //if (time.Date != DateTime.Now.Date)
            {
                var list = GpLocalDataHelper.GetValidGpCodes();

                foreach (var item in list)
                {
                    var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                    dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                    if (dayEnts != null && dayEnts.Count > 0)
                    {
                        bool isRight = true;
                        for (int i = 0; i < num; i++)
                        {
                            var temp = dayEnts[dayEnts.Count - 1 - i];
                            if (temp.Day5Price < temp.Day10Price
                                || temp.Day10Price <= temp.Day20Price
                                || temp.Day20Price <= temp.Day60Price)
                            {
                                isRight = false;
                                break;
                            }
                        }
                        if (isRight)
                        {
                            var tempEnd = dayEnts[dayEnts.Count - 1 - num];
                            if (tempEnd.Day5Price < tempEnd.Day10Price
                            || tempEnd.Day10Price <= tempEnd.Day20Price
                            || tempEnd.Day20Price <= tempEnd.Day60Price)
                            {
                                isRight = true;
                            }
                            else
                            {
                                isRight = false;
                            }
                        }

                        if (isRight)
                        {
                            copyStr += item + "   ";
                        }
                    }
                }
            }
            //else
            //{
            //    List<GpCurEntity> curList = new List<GpCurEntity>();
            //    if (CommonData.TotalGpCount == 0)
            //    {
            //        curList = GpNetDataHelper.GetAllCurGpData().Result;
            //    }
            //    curList = GpNetDataHelper.GetAllCurGpData().Result;

            //    StringBuilder sb = new StringBuilder();

            //    var list = GpLocalDataHelper.GetValidGpCodes();
            //    foreach (var item in curList)
            //    {
            //        if (!list.Contains(item.Code)) continue;
            //        if (item.HighPrice > item.YesClsPrice * moreNum)
            //        {
            //            total++;
            //            if (item.CurPrice >= item.HighPrice)
            //            {
            //                highTotal++;
            //            }
            //            else
            //            {
            //                copyStr += item.Code + "   ";

            //            }
            //        }
            //    }
            //}

            _CopyContent = copyStr;
            File.WriteAllText("MoreRed.txt", copyStr);
            MessageBox.Show("完成");
        }

        private void SecUp_Click(object sender, RoutedEventArgs e)
        {
            if (datePicker.SelectedDate == null) return;
            var time = (DateTime)datePicker.SelectedDate;
            string copyStr = "";
            int total = 0;
            int highTotal = 0;
            float moreNum = 1.095f;
            double blTotal = 0;
            int num = 0;
            float kkTotal = 0;
            var list = GpLocalDataHelper.GetValidGpCodes();

            foreach (var item in list)
            {
                var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                if (dayEnts != null && dayEnts.Count > 0)
                {
                    var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                    if (tempEntIndex > 3)
                    {
                        if (dayEnts[tempEntIndex - 1].MarkUp > 9.5 && dayEnts[tempEntIndex - 2].MarkUp < 9.5)
                        {
                            if (dayEnts[tempEntIndex - 1].PrePrice > dayEnts[tempEntIndex - 2].ClsPrice * moreNum
                                || dayEnts[tempEntIndex].PrePrice > dayEnts[tempEntIndex - 1].ClsPrice * moreNum)
                                continue;

                            if (dayEnts[tempEntIndex].HighPrice > dayEnts[tempEntIndex - 1].ClsPrice * moreNum)
                            {
                                copyStr += item + "   ";
                                total++;
                                if (dayEnts[tempEntIndex].ClsPrice >= dayEnts[tempEntIndex].HighPrice)
                                {
                                    highTotal++;
                                }
                            }
                        }

                    }
                }
            }

            _CopyContent = copyStr;
            File.WriteAllText("MoreRed.txt", copyStr);
            MessageBox.Show(string.Format("总数：{0}，红数：{1}，绿树：{2}", total, highTotal, total - highTotal));
        }

        private void TopOne_Click(object sender, RoutedEventArgs e)
        {
            if (datePicker.SelectedDate == null) return;
            var time = (DateTime)datePicker.SelectedDate;
            string copyStr = "";
            List<string> gps = new List<string>();
            int total = 0;
            int num = 2;
            var list = GpLocalDataHelper.GetValidGpCodes();
            foreach (var item in list)
            {
                var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                if (dayEnts != null && dayEnts.Count > 0)
                {
                    var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                    if (tempEntIndex > 3)
                    {
                        if (dayEnts[tempEntIndex - 1].MarkUp < 9.5
                            && dayEnts[tempEntIndex - 2].MarkUp < 9.5
                            && dayEnts[tempEntIndex].HighPrice >= dayEnts[tempEntIndex - 1].ClsPrice * 1.099)
                        {
                            copyStr += item + "   ";
                            gps.Add(item);
                        }

                    }
                }
            }


            _CopyContent = copyStr;
            //File.WriteAllText("MoreRed.txt", copyStr);
            //MessageBox.Show("完成");
            if(ExportGpImages(time, gps))
                MessageBox.Show("导出成功");
        }
        private bool ExportGpImages(DateTime time, List<string> gps)
        {
            try
            {
                // 创建一个 Bitmap 对象，表示画布
                Bitmap bitmap = new Bitmap(1000, 1000);

                // 创建一个 Graphics 对象，用于在 Bitmap 上绘图
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    // 设置画布背景色
                    graphics.Clear(System.Drawing.Color.White);

                    // 设置绘图字体和颜色
                    Font font = new Font("Arial", 18);
                    SolidBrush brush = new SolidBrush(System.Drawing.Color.Black);

                    float y = 10f; // 纵坐标

                    float x = 10f;
                    // 在画布上逐个绘制成语
                    foreach (string code in gps)
                    {
                        graphics.DrawString(code, font, brush, new PointF(x, y));
                        x += 200;
                        if (x > 1000)
                        {
                            x = 10;
                            y += 40;
                        }
                    }
                }
                string path = time.ToLongDateString() + ".png";
                if (File.Exists(path))
                    File.Delete(path);
                // 保存绘制好的图像为文件
                bitmap.Save(path, ImageFormat.Png);

                // 释放资源
                bitmap.Dispose();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        private void TopPlan1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var list = GpLocalDataHelper.GetValidGpCodes();
                var allGps = GpNetDataHelper.GetAllCurGpData().Result;

                DateTime time = new DateTime(DateTime.Now.Year, 1, 1);
                // 获取有效时间
                var dayList = GpNetDataHelper.GetHistoryDayInfoByCode(CommonData.TargetCode).Result;

                List<TopPlan1Entity> entities = new List<TopPlan1Entity>();
                while (time.CompareTo(DateTime.Now) < 0)
                {
                    if (dayList.Find(x => x.Time == time) == null)
                    {
                        time = time.AddDays(1);
                        continue;
                    }

                    TopPlan1Entity entity = new TopPlan1Entity();
                    entity.Time = time;
                    foreach (var item in list)
                    {
                        var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                        dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                        if (dayEnts != null && dayEnts.Count > 0)
                        {
                            var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                            var curInfo = allGps.Find(x => x.Code == item);
                            if (tempEntIndex > 3 && curInfo != null)
                            {
                                if (dayEnts[tempEntIndex - 1].MarkUp < 9.5
                                    && dayEnts[tempEntIndex - 2].MarkUp < 9.5
                                    && dayEnts[tempEntIndex].HighPrice >= dayEnts[tempEntIndex - 1].ClsPrice * 1.095)
                                {
                                    var value = ((dayEnts[tempEntIndex].ClsPrice * curInfo.TotalMarketValue) / curInfo.CurPrice);

                                    if (dayEnts[tempEntIndex].MarkUp >= 9.5)
                                    {
                                        entity.TopCount++;
                                        if (value < 30)
                                        {
                                            entity.Top0_30++;
                                        }
                                        else if (value >= 30 && value < 50)
                                        {
                                            entity.Top30_50++;
                                        }
                                        else if (value >= 50 && value < 100)
                                        {
                                            entity.Top50_100++;
                                        }
                                        else if (value >= 100 && value < 300)
                                        {
                                            entity.Top100_300++;
                                        }
                                        else if (value >= 300 && value < 1000)
                                        {
                                            entity.Top300_1000++;
                                        }
                                        else if (value >= 1000)
                                        {
                                            entity.Top1000++;
                                        }
                                    }
                                    else
                                    {
                                        entity.NoTopCount++;
                                        if (value < 30)
                                        {
                                            entity.NoTop0_30++;
                                        }
                                        else if (value >= 30 && value < 50)
                                        {
                                            entity.NoTop30_50++;
                                        }
                                        else if (value >= 50 && value < 100)
                                        {
                                            entity.NoTop50_100++;
                                        }
                                        else if (value >= 100 && value < 300)
                                        {
                                            entity.NoTop100_300++;
                                        }
                                        else if (value >= 300 && value < 1000)
                                        {
                                            entity.NoTop300_1000++;
                                        }
                                        else if (value >= 1000)
                                        {
                                            entity.NoTop1000++;
                                        }
                                    }

                                }

                            }
                        }
                    }

                    entities.Add(entity);
                    time = time.AddDays(1);
                }

                GpAnalysisHelper.ExportTopPlan1ToExcel("涨停分析.xlsx", entities);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void TopPlan2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (datePicker.SelectedDate == null) return;
                var time = (DateTime)datePicker.SelectedDate;

                var list = GpLocalDataHelper.GetValidGpCodes();


                List<string> gps = new List<string>();
                float total = 0;
                float high = 0;
                foreach (var item in list)
                {
                    var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year - 1, item);
                    dayEnts.AddRange(GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item));
                    if (dayEnts.Count > 0)
                    {
                        var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                        if (tempEntIndex <= 0 || tempEntIndex >= dayEnts.Count - 1)
                            continue;
                        if (dayEnts[tempEntIndex].PrePrice >= GetTopPrice(dayEnts[tempEntIndex - 1].ClsPrice - 0.01))
                            continue;
                        if (dayEnts[tempEntIndex - 1].ClsPrice < GetTopPrice(dayEnts[tempEntIndex - 2].ClsPrice)
                            || dayEnts[tempEntIndex].HighPrice < GetTopPrice(dayEnts[tempEntIndex - 1].ClsPrice) - 0.01)
                            continue;
                        var ent98 = dayEnts.GetRange(tempEntIndex - 6, 5).Find(x => x.MarkUp >= 9.8);
                        if (ent98 != null)
                            continue;
                        gps.Add(item);
                        total += (dayEnts[tempEntIndex + 1].ClsPrice - dayEnts[tempEntIndex].ClsPrice) / dayEnts[tempEntIndex].ClsPrice * 100;
                        high += (dayEnts[tempEntIndex + 1].HighPrice - dayEnts[tempEntIndex].ClsPrice) / dayEnts[tempEntIndex].ClsPrice * 100;
                    }
                }

                MessageBox.Show($"总{total / gps.Count}; 高{high / gps.Count}");

                ExportGpImages(time, gps);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private double GetTopPrice(double clsPrice)
        {
            double topOffset = Math.Round(clsPrice * 0.1, 2, MidpointRounding.AwayFromZero);
            var mark = Math.Round(topOffset / clsPrice * 100, 2, MidpointRounding.AwayFromZero);
            return (clsPrice * (1 + mark / 100.0));
        }

        /// <summary>
        /// Macd配合kdj
        /// Macd底背离，KDJ金叉
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MacdKdjPlan_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (datePicker.SelectedDate == null) return;
                var time = (DateTime)datePicker.SelectedDate;

                var list = GpLocalDataHelper.GetValidGpCodes();
                List<string> gps = new List<string>();

                foreach (var item in list)
                {
                    var dayEnts = GpLocalDataHelper.GetLocalHistoryDayInfoByCode(time.Year, item);
                    if(dayEnts.Count > 0)
                    {
                        var tempEntIndex = dayEnts.FindIndex(x => x.Time == time);
                        if (tempEntIndex - 10 < 0)
                            continue;
                        var tempEnts = dayEnts.GetRange(tempEntIndex - 9, 10);
                        // macd上升趋势
                        if (!IsUpward(tempEnts.Select(x => x.MACD).ToList()))
                            continue;
                        // macd水下
                        if (!IsBottomPartMore(tempEnts.Select(x => x.MACD).ToList(), 0))
                            continue;
                        if (!IsBottomPartMore(tempEnts.Select(x => x.DIF).ToList(), 0))
                            continue;
                        if (!IsBottomPartMore(tempEnts.Select(x => x.DEA).ToList(), 0))
                            continue;
                        if (!IsBottomPartMore(tempEnts.Select(x => x.DEA).ToList(), 0))
                            continue;

                        if (!IsUpward(tempEnts.Select(x => x.J).ToList()))
                            continue;
                        if (!IsBottomPartMore(tempEnts.Select(x => x.J - x.D).ToList(), 0))
                            continue;
                        gps.Add(item);

                    }
                }
                ExportGpImages(time, gps);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private bool IsUpward(List<float> values, double threshold = 0.8)
        {
            if (values.Count <= 1) return false;
            int upwardNum = 0;
            for (int i = 1; i < values.Count; i++)
            {
                if (values[i] > values[i - 1])
                {
                    upwardNum++;
                }
            }
            return (upwardNum / values.Count) >= threshold;
        }
        private bool IsBottomPartMore(List<float> values, float tol, double threshold = 0.8)
        {
            if (values.Count <= 1) return false;
            int bottomNum = 0;
            for (int i = 0; i < values.Count; i++)
            {
                if (values[i] <= tol)
                {
                    bottomNum++;
                }
            }
            return (bottomNum / values.Count) >= threshold;
        }
    }
}
